package top.yongyan0624.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Yongyan
 * @description
 * @date 2022/2/8 15:20
 **/
public class MyApplicationContext {

    private Class configClass;

    //Bean的信息对象，Bean名字:BeanDefinition信息对象
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    //单例池，Bean名字:Bean实例
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    //Bean的后置处理器集合
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public MyApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 通过配置类的扫描路径扫描-->得到很多BeanDefinition对象-->存到beanDefinitionMap中
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            //获取配置类上的注解
            ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            //通过注解获取扫描相对路径
            String path = componentScan.value(); // top.yongyan0624.service

            //通过ClassLoader获取绝对路径
            ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path.replace(".", "/"));// top/yongyan0624/service

            //通过绝对路径获取到service目录
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String filePath = f.getAbsolutePath();  //得到目录下的所有文件路径
                    if (filePath.endsWith(".class")) {      //如果是class文件，则解析出它的全限定名
                        String className = path + "." + filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.indexOf(".class"));
                        try {
                            //通过全限定名获取字节码对象
                            Class<?> clazz = classLoader.loadClass(className);
                            if (clazz.isAnnotationPresent(Component.class)) {
                                //如果类上有Component注解，代表它是个Bean

                                //如果这个Bean比较特殊，是个后置处理器，需要将它加入到后置处理器集合中
                                //可以通过后置处理器接口的class类的isAssignableFrom方法 判断 当前的Bean是不是自己的子类，由此判断是否是个后置处理器
                                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(beanPostProcessor);
                                }

                                //通过注解获取Bean对象的名字
                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                if (beanName.equals("")) {
                                    //如果没有指明这个Bean的名字，则默认用类名的小驼峰作为Bean名字
                                    //生成小驼峰可以用一个工具类的方法，传入class类的短名即可
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                //接下来并不是直接进行Bean的实例化，而是要实例化初始化一个BeanDefinition信息对象保存Bean的信息
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scope = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scope.value());
                                } else {
                                    beanDefinition.setScope("singleton");
                                }

                                //接下来需要把这个BeanDefinition对象存起来，方便以后使用
                                beanDefinitionMap.put(beanName, beanDefinition);

                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        //扫描结束后，实例化单例对象
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            //实例化
            Object instance = clazz.getConstructor().newInstance();
            //初始化内部的属性，依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            //Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //调用后置器的前置方法
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }

            //初始化操作：只需要实现对应接口，Spring就允许开发者进行某些自定义初始化操作
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            //调用后置器的后置方法
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }

            //模拟AOP：利用BeanPostProcessor后置处理器机制，返回代理对象当做Bean的实例 ↑

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            //不存在这个Bean
            throw new NullPointerException();
        }
        String scope = beanDefinition.getScope();
        if (scope.equals("singleton")) {
            //单例
            Object bean = singletonObjects.get(beanName);
            if (bean == null) {
                bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
            return bean;
        } else {
            //多例
            return createBean(beanName, beanDefinition);
        }
    }
}
